package com.word.web.service;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

@Service
public class LocalHotpotAPIService {
    private final List<String> routes = new ArrayList<>();
    private Random random;

    @Scheduled(initialDelay = 1000, fixedRate = 86400000)
    public void fixedUpdate() {
        HttpRequest req = HttpRequest.get("http://localhost:6688/all");
        HttpResponse res = req.execute();
        JSONObject jsonObject = JSONObject.parseObject(res.body());
        String code = jsonObject.getString("code");
        routes.clear();
        if ("200".equals(code)) {
            JSONArray jsonArray = jsonObject.getJSONArray("routes");
            for (int i = 0; i < jsonArray.size(); i++) {
                JSONObject object = jsonArray.getJSONObject(i);
                if (object == null) continue;
                String path = object.getString("path");
                if (path == null || "null".equals(path)) continue;
                routes.add(path);
            }
        }
        random = new Random();
    }

    public String get() {
        try {
            int index = random.nextInt(routes.size());
            String path = routes.get(index);
            HttpRequest req = HttpRequest.get("http://localhost:6688" + path);
            HttpResponse res = req.execute();
            JSONObject jsonObject = JSONObject.parseObject(res.body());
            JSONArray array = jsonObject.getJSONArray("data");
            int randomDataIndex = random.nextInt(array.size());
            JSONObject randomItem = array.getJSONObject(randomDataIndex);
            return randomItem.getString("title");
        } catch (Exception e) {
            return null;
        }
    }
}
